/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    @Bean(name = "op2ParseExecutor")
    public ExecutorService op2ParseExecutor() {
        return new ThreadPoolExecutor(
            CPU_COUNT,                          // 核心线程数，根据机器和任务调节
            CPU_COUNT * 2,                          // 最大线程数
            60L, TimeUnit.SECONDS,      // 空闲线程存活时间
            new LinkedBlockingQueue<>(20), // 队列容量，避免任务无限堆积
            new NamedThreadFactory("op2-parse"),
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：线程饱和时由调用线程执行任务
        );
    }

    @Bean(name = "bdfParseExecutor")
    public ExecutorService bdfParseExecutor() {
        return new ThreadPoolExecutor(
            CPU_COUNT,                          // 核心线程数，根据机器和任务调节
            CPU_COUNT * 2,                    // 最大线程数
            60L, TimeUnit.SECONDS,      // 空闲线程存活时间
            new LinkedBlockingQueue<>(20), // 队列容量，避免任务无限堆积
            new NamedThreadFactory("bdf-parse"),
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：线程饱和时由调用线程执行任务
        );
    }


    // io密集型
    @Bean(name = "mongoBatchExecutor")
    public  ExecutorService mongoBatchExecutor() {
        return new ThreadPoolExecutor(
            CPU_COUNT * 2,                          // 核心线程数，根据机器和任务调节
            CPU_COUNT * 5,                          // 最大线程数
            60L, TimeUnit.SECONDS,      // 空闲线程存活时间
            new LinkedBlockingQueue<>(100), // 队列容量，避免任务无限堆积
            new NamedThreadFactory("mongo-batch"),
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：线程饱和时由调用线程执行任务
        );
    }
}
